import * as fs from 'fs';
import * as path from 'path';
import { Logger } from '../../../../src/logger/Logger';

/**
 * UT BUILD.gn 更新器
 * 负责在合适的位置创建或更新 group("unittest")，并把新生成的 ohos_unittest 目标注册进去
 */
export class UTBuildGNUpdater {
  /**
   * 在指定目录（通常是 test/unittest 的父级）创建基础 BUILD.gn（若不存在）并包含 group("unittest")
   */
  public static ensureParentGroupBuildGN(parentDir: string): string | null {
    try {
      const gnPath = path.join(parentDir, 'BUILD.gn');
      if (!fs.existsSync(gnPath)) {
        const year = new Date().getFullYear();
        const content = `# Copyright (c) ${year} Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import("//build/test.gni")

group("unittest") {
  testonly = true
  deps = []
}
`;
        fs.writeFileSync(gnPath, content, 'utf-8');
        Logger.info(`[UTBuildGNUpdater] ✅ 已创建父级 BUILD.gn: ${gnPath}`);
      } else {
        // 若存在但没有 group("unittest")，追加一个空 group
        const content = fs.readFileSync(gnPath, 'utf-8');
        if (!/group\s*\(\s*["']unittest["']\s*\)\s*\{[\s\S]*?\}/.test(content)) {
          const appended = content.trimEnd() + `

group("unittest") {
  testonly = true
  deps = []
}
`;
          fs.writeFileSync(gnPath, appended, 'utf-8');
          Logger.info(`[UTBuildGNUpdater] ✅ 已在父级 BUILD.gn 中追加 group("unittest"): ${gnPath}`);
        }
      }
      return gnPath;
    } catch (e: any) {
      Logger.error(`[UTBuildGNUpdater] ❌ ensureParentGroupBuildGN 失败: ${e?.message || e}`);
      return null;
    }
  }

  /**
   * 将子目录 target 注册到某个 BUILD.gn 的 group("unittest") 的 deps 中
   * @param groupBuildGnPath 包含 group("unittest") 的 BUILD.gn 路径
   * @param relativeDir 子目录相对路径（例如 ./unittest 或 ./unittest/module_a）
   * @param testTargetName 新建的 ohos_unittest 目标名
   */
  public static registerToGroup(groupBuildGnPath: string, relativeDir: string, testTargetName: string): boolean {
    try {
      if (!fs.existsSync(groupBuildGnPath)) {
        Logger.warn(`[UTBuildGNUpdater] group BUILD.gn 不存在: ${groupBuildGnPath}`);
        return false;
      }
      let content = fs.readFileSync(groupBuildGnPath, 'utf-8');
      const depPath = `${relativeDir.startsWith('.') ? '' : './'}${relativeDir.replace(/\\/g, '/').replace(/\/$/, '')}:${testTargetName}`
        .replace(/^\.\//, './');

      // 若已存在则跳过
      if (content.includes(`"${depPath}"`)) {
        Logger.info(`[UTBuildGNUpdater] ℹ️  已存在依赖 ${depPath}（跳过）`);
        return true;
      }

      // 定位 group("unittest") 的 deps 数组
      const groupRegex = /group\s*\(\s*["']unittest["']\s*\)\s*\{[\s\S]*?deps\s*=\s*\[([\s\S]*?)\][\s\S]*?\}/m;
      const match = content.match(groupRegex);
      if (!match) {
        Logger.warn(`[UTBuildGNUpdater] ⚠️ 未找到 group("unittest")，无法注册 ${depPath}`);
        return false;
      }

      const depsContent = match[1];
      const updatedDeps = depsContent.trim()
        ? `${depsContent.trim()},\n    "${depPath}"`
        : `\n    "${depPath}"\n  `;

      content = content.replace(
        groupRegex,
        (full) => full.replace(/deps\s*=\s*\[[\s\S]*?\]/m, `deps = [${updatedDeps}]`)
      );

      fs.writeFileSync(groupBuildGnPath, content, 'utf-8');
      Logger.info(`[UTBuildGNUpdater] ✅ 已更新 ${groupBuildGnPath}，添加 ${depPath}`);
      return true;
    } catch (e: any) {
      Logger.error(`[UTBuildGNUpdater] ❌ registerToGroup 失败: ${e?.message || e}`);
      return false;
    }
  }
}


